package bulkyshare.project.de.bulkyshare.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import bulkyshare.project.de.bulkyshare.R;

/**
 * @author Alexander Radtke
 * @version 1.0
 *
 * This Activity represents the NavigationDrawer.
 * Every other Fragment View can be reached from here.
 */
public class MainActivity extends Activity {
    private DrawerLayout drawerLayout;
    private ListView drawerList;
    private ArrayAdapter<String> drawerListAdapter;
    private ActionBarDrawerToggle drawerToggle;

    // Name of the application
    private String app_title, user_id;
    // Current selected Navigation Drawer item name
    private String drawer_title;
    // All Navigation Drawer items. Array is filled with R.array.navigation_drawer_values
    private String[] drawerTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // We need to get the user id from the login
        Bundle info = getIntent().getExtras();
        if (info != null) {
            user_id = info.getString("user_id");
            Log.d("user_id", "User id from logged in user: " + user_id);
        }

        app_title = drawer_title = getTitle().toString();
        drawerTitles = getResources().getStringArray(R.array.navigation_drawer_values);

        drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer_layout);
        drawerList = (ListView) findViewById(R.id.navigation_drawer_list);

        drawerListAdapter = new ArrayAdapter<String>(this, R.layout.drawer_textview, drawerTitles);
        drawerList.setAdapter(drawerListAdapter);

        drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        // Display the ic_drawer icon
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(drawer_title);
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(app_title);
                // Refresh the options menu because the items may have changed
                invalidateOptionsMenu();
            }
        };
        // Notified when Drawer events occur
        drawerLayout.setDrawerListener(drawerToggle);
        // Handle clicks on Navigation Drawer items
        drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
                // Change view to pos
                changeView(pos);
            }
        });

        // When no other Fragment is selected (happens when the app is started), then select the first.
        // The first Fragment is always PickupDatesNearby
        if (savedInstanceState == null) {
            changeView(0);
        }
    }

    /**
     * Changes the View through a FragmentManager.
     * @param pos Position of the fragment inside the navigation drawer.
     *            For example the PickupDateNearby Fragment is 0.
     */
    private void changeView(int pos) {
        Fragment frag = null;
        Bundle extras = new Bundle();
        // Pass the user_id to all fragments for database queries.
        extras.putString("user_id", user_id);
        switch (pos) {
            case 0:
                frag = new PickupDatesNearby();
                break;
            case 1:
                frag = new MyPickupDates();
                break;
            case 2:
                frag = new Profile();
                break;
            case 3:
                // Logout.
                onLogoutDialog();
                break;
            default:
                break;
        }

        if (frag != null) {
            // Replace currently viewed View with the selected Fragment
            FragmentManager fragmentManager = getFragmentManager();
            frag.setArguments(extras);
            fragmentManager.beginTransaction().replace(R.id.content_frame, frag).commit();

            // Update the navigation drawer (set selected item checked, close Drawer) and change the title
            drawerList.setItemChecked(pos, true);
            drawerList.setSelection(pos);
            setTitle(drawerTitles[pos]);
            drawerLayout.closeDrawer(drawerList);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu.
        // We don't have a Menu for the Navigation Drawer
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar item events if there are any
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void setTitle(CharSequence title) {
        drawer_title = title.toString();
        getActionBar().setTitle(drawer_title);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration configuration) {
        super.onConfigurationChanged(configuration);
        drawerToggle.onConfigurationChanged(configuration);
    }

    /**
     * Asks the user if he really wants to log himself out after confirming this dialog
     * the user will be forwarded back to the login-screen. This method also removes
     * the SharedPreferences value for the maximal search range.
     */
    private void onLogoutDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle(R.string.logout);
        builder.setMessage(R.string.logout_message);
        builder.setPositiveButton(getString(R.string.logout), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
                preferences.edit().remove("max_distance").commit();
                finish();
                startActivity(new Intent(MainActivity.this, Login.class));
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        AlertDialog logout = builder.create();
        logout.show();
    }
}
